﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace PolePosition.v3.DesktopFactory
{
    public class DownloadFile: IDisposable
    {
        protected Uri m_FileUrl;
        protected FileInfo m_FileDestination;
        protected WebClient m_WebClient = new WebClient();

        public void SetUrl(string url)
        {
            m_FileUrl = new Uri(url);
        }

        public void SetFileDestination(string destinationPath)
        {
            m_FileDestination = new FileInfo(destinationPath);
        }

        public DownloadFile(string url, string destinationPath)
            : this()
        {
            m_FileUrl = new Uri(url);
            m_FileDestination = new FileInfo(destinationPath);
        }

        public DownloadFile()
        {
            m_WebClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(WebClient_DownloadFileCompleted);
            m_WebClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WebClient_DownloadProgressChanged);
        }

        #region IDisposable Members

        public void Dispose()
        {
            m_WebClient.DownloadFileCompleted -= new System.ComponentModel.AsyncCompletedEventHandler(WebClient_DownloadFileCompleted);
            m_WebClient.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(WebClient_DownloadProgressChanged);
        }

        #endregion
        public void StartDownload()
        {
            m_WebClient.DownloadFileAsync(m_FileUrl, m_FileDestination.FullName);
        }

        public void CancelDownload()
        {
            m_WebClient.Dispose();
        }

        #region WebClientEvents
        
        private void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            OnFinishDownloadFile(sender, new EventArgs());
        }

        private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            OnProgressChanged(sender, e);
        }

        #endregion

        #region DownloadFile Events

        public event EventHandler FinishDownloadFile;
        public void OnFinishDownloadFile(object o, EventArgs e)
        {
            // Safely invoke an event:
            if (FinishDownloadFile != null)
            {
                FinishDownloadFile(o, e);
            }
        }

        public event EventHandler<DownloadProgressChangedEventArgs> ProgressChanged;
        private void OnProgressChanged(object o, DownloadProgressChangedEventArgs e)
        {
            // Safely invoke an event:
            if (ProgressChanged != null)
            {
                ProgressChanged(o, e);
            }
        }

        #endregion
   
    }
}
